package cn.com.zetatech.loader.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Value("${async.executor.thread.core_pool_size:5}")
    private int corePoolSize;
    @Value("${async.executor.thread.max_pool_size:5}")
    private int maxPoolSize;
    @Value("${async.executor.thread.queue_capacity:200}")
    private int queueCapacity;

    @Bean("resolverTaskExecutor")
    public Executor resolverTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中线程的名称前缀
        executor.setThreadNamePrefix("resolver-async-");
        // 拒绝策略：由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }

    @Bean("monitorExecutor")
    public Executor monitorExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize*2);
        //配置最大线程数
        executor.setMaxPoolSize(corePoolSize*2);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中线程的名称前缀
        executor.setThreadNamePrefix("monitor-async-");
        // 拒绝策略：新建一个线程处理
        RejectedExecutionHandler rejectedExecutionHandler = (r, executor_) -> {
            Thread thread = new Thread(() -> {
                r.run();
            });
            thread.setName("monitor-async-rejected-" + thread.getId());
            thread.start();
        };
        executor.setRejectedExecutionHandler(rejectedExecutionHandler);
        //执行初始化
        executor.initialize();
        return executor;
    }
}
